package com.example.web.servlet;

import com.example.dao.UserDao;
import com.example.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
//        //2.获取用户名和密码
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        //3.封装user对象（用户输入的用户名和密码）
//        User loginUser = new User();
//        loginUser.setUsername(username);
//        loginUser.setPassword(password);

        //2.用BeanUtils工具获取所有请求参数
        Map<String, String[]> map = request.getParameterMap();
        //3.创建User对象
        User loginUser = new User();
        //4.使用BeanUtils封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //调用UserDao里的login（）方法（查询数据库真正的用户名和密码）
        User user = new UserDao().login(loginUser);
        if (user == null) {
            request.getRequestDispatcher("/failServlet").forward(request, response);
        } else {
            request.setAttribute("username", user);
            request.getRequestDispatcher("/successServlet").forward(request, response);

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
